#include "musicslider.h"
#include "ui_musicslider.h"

#include <QMouseEvent>
#include <QDebug>

MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);

    currentPos = 0;
    maxWidth = width();
    moveSilder();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::setStep(float ratio)
{
    currentPos = maxWidth * ratio;
    moveSilder();
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    QRect rect = QRect(0,0,width(),height());
    if(!rect.contains(event->pos()))
    {
        return ;
    }

    if(event->buttons() == Qt::LeftButton)
    {
        currentPos = event->pos().x();
        if(currentPos > maxWidth)
        {
            currentPos = maxWidth;
        }
        if(currentPos < 0)
        {
            currentPos = 0;
        }
        moveSilder();
    }
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    if(currentPos > maxWidth)
    {
        currentPos = maxWidth;
    }
    if(currentPos < 0)
    {
        currentPos = 0;
    }
    moveSilder();
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    if(currentPos > maxWidth)
    {
        currentPos = maxWidth;
    }
    if(currentPos < 0)
    {
        currentPos = 0;
    }
    moveSilder();

    //修改当前播放时间
    emit setMusicSliderPosition(currentPos / (float)maxWidth);
}

void MusicSlider::moveSilder()
{
    ui->outLine->setGeometry(0,8,currentPos,4);
}
